package com.webserver.core;

import com.webserver.controller.UserController;
import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.File;
import java.net.URISyntaxException;

public class DispatcherServlet {
    private static File root;
    private static File staticDir;

    static {
        try {
            root = new File(DispatcherServlet.class.getClassLoader().getResource(".").toURI());
            staticDir = new File(root, "static");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    public DispatcherServlet() {
    }

    public void service(HttpServletRequest request, HttpServletResponse response) {

        Thread thread = Thread.currentThread();
        System.out.println("4444444444444444444444444444444当前线程为：" + thread + "4444444444444444444444444444");


        String path = request.getRequestURI();


        System.out.println("------------------------------------------------------");
        System.out.println("1111111111111此时路径path为：" + path);


        if ("/myweb/reg".equals(path)) {//判断注册业务
            System.out.println("---是注册业务---");
            UserController reg = new UserController();
            reg.reg(request, response);

        } else if ("/myweb/login".equals(path)) {//判断登录业务
            System.out.println("---是登陆业务---");
            UserController login = new UserController();
            login.login(request, response);
        } else if ("/myweb/writeArticle".equals(path)) {
            System.out.println("---是写文章业务---");
            UserController article = new UserController();
            article.writeArticle(request, response);

        } else {//判断是否为打开页面要求

            System.out.println("---是打开页面业务---");
            File file = new File(staticDir, path);
            if (file.isFile()) {
                response.setContentFile(file);
            } else {
                response.setStatusCode(404);
                response.setStatusReason("NotFound");
                file = new File(staticDir, "/root/404.html");
                response.setContentFile(file);
            }
        }

    }
}
